package com.sinodata.bsm.cicp.collector.common;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-20 15:37:12      liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class WebService extends Collector {
    //    private static final Logger logger = Logger.getLogger(WebService.class.getName());

    @Override
    public List<ResPropertyValue> collect(String ip) {
        String SOAPUrl = this.getParamMap().get("URL Address").trim();//URL地址
        String req = this.getParamMap().get("Requested xml Information").trim();//请求信息
        String timeout = this.getParamMap().get("Timeout Time").trim();//超时时间
        String resverify = this.getParamMap().get("Verification Condition").trim();//验证条件
        Long[] colret = { -1l, 0l };
        String message = "N/A";
        int timeOut = Integer.parseInt(timeout);
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        ;
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        long startTime = System.currentTimeMillis();
        try {
            //		    String SOAPUrl = "http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx";
            //		    StringBuffer sb = new StringBuffer();
            //		    sb.append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"");
            //			sb.append(" xmlns:web=\"http://WebXml.com.cn/\">").append("\n");
            //			sb.append("<soap:Header/>").append("\n");
            //			sb.append("<soap:Body>").append("\n");
            //			sb.append("<web:getMobileCodeInfo>").append("\n");
            //			sb.append("<!--Optional:-->").append("\n");
            //			sb.append("<web:mobileCode>13810191077</web:mobileCode>").append("\n");
            //			sb.append("</web:getMobileCodeInfo>").append("\n");
            //			sb.append("</soap:Body>").append("\n");
            //			sb.append("</soap:Envelope>").append("\n");
            //	    String req=sb.toString();
            //	    int timeOut = 10000;
            //	    String resverify = "getMobileCodeInfoResult=13810191077:北京 北京 北京移动动感地带卡";
            colret[1] = do_collect(SOAPUrl, req, timeOut, resverify, colret, message);
        } catch (Exception e) {
            if (e instanceof java.net.SocketTimeoutException) {
                colret[1] = 2l;

            } else if (e instanceof java.io.IOException) {
                colret[1] = 1l;

            } else {
                colret[1] = -1l;

            }
            message = e.getMessage();

        } finally {
            colret[0] = System.currentTimeMillis() - startTime;
            propValues[0] = ResPropertyValue.createPropValue(colret[0].toString(), propMetas[0]);
            propValues[1] = ResPropertyValue.createPropValue(colret[1].toString(), propMetas[1]);
            propValues[2] = ResPropertyValue.createPropValue(message, propMetas[2]);
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
        }
        return values;
    }

    @Override
    public String[] getParamMeta() {
        //        return new String[] { "URL地址", "请求信息", "超时时间", "验证条件" };
        return new String[] { "URL Address", "Requested xml Information", "Timeout Time", "Verification Condition" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "Response_Time", "status:(0:normal,1:unavailable,2:overtime,3:SOAP failure,4:failed verification,-1:other)", "Information" };
    }

    private long do_collect(String url, String req, int timeout, String verify, Long[] result, String message) throws Exception {
        byte[] b = req.getBytes();
        URLConnection connection = new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        HttpURLConnection httpConn = (HttpURLConnection) connection;
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream os = httpConn.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
        os.write(b);
        //osw.write(req);
        osw.flush();
        osw.close();
        InputStream ins = httpConn.getInputStream();
        InputStreamReader isr = new InputStreamReader(ins, "utf-8");
        java.io.BufferedReader br = new java.io.BufferedReader(isr);
        String soapxml = br.readLine();
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
            }
            br = null;
        }
        //		     SAXReader reader = new SAXReader();
        //            Document docResponse = reader.read(soapxml);

        //Element root = docResponse.getRootElement();
        //		    Document document = DocumentHelper.createDocument();
        //            Element root = document.addElement("Body");
        //			<?xml version="1.0" encoding="utf-8"?><soap:Envelope
        //			 xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://
        //			 www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/
        //			 XMLSchema"><soap:Body><getMobileCodeInfoResponse xmlns="http://
        //			 WebXml.com.cn/"><getMobileCodeInfoResult>13810191077:北京 北京 北京移动动感地带
        //			 卡</getMobileCodeInfoResult></getMobileCodeInfoResponse></soap:Body></
        //			 soap:Envelope>

        Document docResponse = DocumentHelper.parseText(soapxml);
        Element root = docResponse.getRootElement();
        Node body = root.selectSingleNode("soap:Body");

        if (body.selectNodes("Fault").size() > 0) {
            //            Node fault = body.selectSingleNode("Fault");
            //            Node code = fault.selectSingleNode("Code");
            //            String Code = ((Element) code).attributeValue("Code");
            //            Node reason = fault.selectSingleNode("Reason");
            //            String Reason = ((Element) reason).attributeValue("Reason");
            //            message = code.getText() + reason.getText();
            return 3;
        }
        if (verify == "") {
            return 0;
        }
        String[] ss = verify.split("=", 2);
        if (ss.length == 2) {
            String name = ss[0];
            List<Node> vers = root.selectNodes("//" + name + "");
            for (Node ver : vers) {
                if (ver != null && ver.getText() == ss[1]) {
                    return 0;
                }
            }
            for (Iterator i = ((Element) body).elementIterator(name); i.hasNext();) {
                Element foo = (Element) i.next();
                if (foo != null && foo.getText() == ss[1]) {
                    return 0;
                }
            }
            for (Iterator i = ((Element) body).elementIterator("getMobileCodeInfoResponse"); i.hasNext();) {
                Element foo = (Element) i.next();
                if (foo != null && foo.getText() == ss[1]) {
                    return 0;
                }
                for (Iterator j = foo.elementIterator(name); j.hasNext();) {
                    Element foo1 = (Element) j.next();
                    if (foo1 != null && foo1.getText().equals(ss[1])) {
                        return 0;
                    }
                }
            }
            return 4;
        }
        return -1;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        WebService webs = new WebService();
        webs.collect("1");
    }

}
